package com.atguigu.yygh.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author luoyin
 * @Date 18:35 2022/9/20
 **/
@Component
@Slf4j
@Aspect
public class LogAspect {

    @Pointcut("execution(* *..*.controller..*.*(..))")
    public void controllerAspect() {
    }

    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint pjp ) throws Throwable {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //请求方式
        String method = request.getMethod();
        //请求路径
        String url = request.getRequestURL().toString();
        //ip
        String ip = request.getRemoteAddr();
        //类名
        String className = pjp.getSignature().getDeclaringTypeName();
        //方法名
        String methodName = pjp.getSignature().getName();
        //方法参数
        Object[] args = pjp.getArgs();
        StringBuilder params = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            if (i == args.length - 1) {
                params.append("param" + (i + 1) + ":" + args[i]);
            } else {
                params.append("param" + (i + 1) + ":" + args[i] + ",");
            }

        }
        Long startTime = 0L;
        try {
            startTime = System.currentTimeMillis();
            return pjp.proceed();
        } finally {
            Long endTime = System.currentTimeMillis();
            Long time = endTime - startTime;
            log.info("用户编号 : " + null
                    + " -- 用户名 : " + null
                    + " -- 请求路径 : " + url
                    + " -- 请求方式 : " + method
                    + " -- ip地址 : " + ip
                    + " -- 类名 : " + className
                    + " -- 方法名 : " + methodName
                    + " -- 参数 : " + (params.toString().equals("") ? "无参数" : params)
                    + " -- 运行时长 : " + time + "毫秒");
        }
    }
}
